import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test_demo/model/index.dart';
import 'package:flutter_test_demo/pages/order_bloc/view.dart';
import 'package:flutter_test_demo/pages/order_event_bloc/view.dart';
import 'package:flutter_test_demo/pages/shop_cart_bloc/view.dart';

import 'cubit.dart';
import 'state.dart';

class HomeBlocPage extends StatefulWidget {
  const HomeBlocPage({super.key});

  @override
  State<HomeBlocPage> createState() => _HomeBlocPageState();
}

class _HomeBlocPageState extends State<HomeBlocPage> {

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => HomeBlocCubit(),
      child: Builder(builder: (context) => _buildPage(context)),
    );
  }

  Widget _buildPage(BuildContext context) {
    final cubit = BlocProvider.of<HomeBlocCubit>(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品列表'),
        centerTitle: true,
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            onPressed: () {
              // Get.toNamed(RouterName.shopCartPage)?.then((e) {
              //   logic.queryGoodsList();
              // });
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const ShopCartBlocPage()),
              ).then((v) {
                cubit.queryGoodsList();
              });
            },
            icon: const Icon(Icons.shopping_cart),
          ),
          IconButton(
            onPressed: (){
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => OrderEventBlocPage()),
                //   MaterialPageRoute(builder: (context) => OrderBlocPage())
              );
            },
            icon: const Icon(Icons.book),
          )
        ],
      ),
      body: _buildContentWidget(cubit),
    );
  }

  Widget _buildContentWidget(HomeBlocCubit cubit) {
    return Column(
      children: [
        BlocBuilder<HomeBlocCubit, HomeBlocState>(
          builder: (context, state) {
            return _buildGoodsList(cubit);
          },
        ),
        _buildBottomWidget(context, cubit)
      ],
    );
  }

  Widget _buildGoodsList(HomeBlocCubit cubit) {
    if(cubit.state.goodsList.isEmpty) {
      return const Expanded(child: Center(child: Text("暂无数据", style: TextStyle(fontSize: 14),)));
    }
    return Expanded(
      child: BlocBuilder<HomeBlocCubit, HomeBlocState>(
        builder: (context, state) {
          print('state.goodsList.length:${state.goodsList.length}');
          return ListView.separated(
              itemBuilder: (context, index){
                GoodsListModel model = cubit.state.goodsList[index];
                return _buildItemWidget(model, cubit);
              },
              separatorBuilder: (context, index){
                return Container(height: 10);
              },
              itemCount: cubit.state.goodsList.length,
              shrinkWrap: true,
              padding: const EdgeInsets.all(12),
            );
        },
      ),
    );
  }

  Widget _buildItemWidget(GoodsListModel model, HomeBlocCubit cubit) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8)
      ),
      child: Row(
        children: [
          Container(
            color: const Color(0xFFdddddd),
            width: 100,
            height: 100,
            child: const Icon(Icons.image),
          ),
          const SizedBox(width: 12,),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(model.goodsName ?? '', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),),
                _buildSizedBoxWidget(),
                Text("商品编码：${model.goodsCode ?? ''}", style: const TextStyle(fontSize: 14),),
                _buildSizedBoxWidget(),
                _buildCountWidget(model, cubit)
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCountWidget(GoodsListModel model, HomeBlocCubit cubit) {
    return Row(
      children: [
        Text("￥${model.goodsPrice}", style: const TextStyle(fontSize: 14, color: Color(0xFF666666)),),
        Expanded(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              InkWell(
                onTap: () => cubit.addCount(model),
                child: _buildContainerWidget(
                  widget: const Text("+", style: TextStyle(fontSize: 16),),
                ),
              ),
              const SizedBox(width: 6,),
              BlocBuilder<HomeBlocCubit, HomeBlocState>(
                builder: (context, state) {
                  return _buildContainerWidget(
                    widget: Text("${model.goodsQty}", style: const TextStyle(fontSize: 16),),
                  );
                },
              ),
              const SizedBox(width: 6,),
              InkWell(
                onTap: () => cubit.subCount(model),
                child: _buildContainerWidget(
                  widget: const Text("-", style: TextStyle(fontSize: 16),),
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  Widget _buildContainerWidget({required Widget widget}) {
    return Container(
      width: 30,
      height: 30,
      color: const Color(0xFFDDDDDD),
      child: Center(child: widget,),
    );
  }

  Widget _buildBottomWidget(BuildContext context, HomeBlocCubit cubit) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
      child: _buildButtonWidget(context, cubit),
    );
  }

  Widget _buildButtonWidget(BuildContext context, HomeBlocCubit cubit) {
    return BlocBuilder<HomeBlocCubit, HomeBlocState>(
      builder: (context, state) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              "共计：${cubit.totalPrice()}",
              style: const TextStyle(fontSize: 14),
            ),
            InkWell(
              onTap: () => cubit.addCart(context),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
                decoration: BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.circular(4)
                ),
                child: const Text('加入购物车', style: TextStyle(color: Colors.white),),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildSizedBoxWidget() {
    return const SizedBox(height: 10);
  }

}


